let createError = require('http-errors');
let express = require('express');
let path = require('path');
let cookieParser = require('cookie-parser');
let logger = require('morgan');
let multer = require('multer');
const md5 = require('md5');
const session = require('express-session')
const whiteList = require('./routes/whiteList');
const { expressjwt } = require('express-jwt');
const { ValidationError, ServiceError, UnknownError, UploadError } = require('./utils/errors')



// 引入数据库连接 
require('dotenv').config()
require('./dao/db')

require('express-async-errors')


// 一定要先连接数据库 在引入路由
let uploadRouter = require('./routes/upload');
let adminRouter = require('./routes/admin');
let captchaRouter = require('./routes/captcha');
let bannerRouter = require('./routes/banner');
let blogTypeRouter = require('./routes/blogType');
let blogRouter = require('./routes/blog');



// 创建实例
let app = express();
app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: true,
  saveUninitialized: true
}))

// 使用中间件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 验证
app.use(expressjwt({
  secret: md5(process.env.JWT_SECRET),
  algorithms: ['HS256']
}).unless({ path: whiteList }));

// 使用路由
app.use('/api/upload', uploadRouter);
app.use('/api/admin', adminRouter);
app.use('/api/banner', bannerRouter);
app.use('/res/captcha', captchaRouter);
app.use('/api/blogtype', blogTypeRouter);
app.use('/api/blog', blogRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// 错误处理
app.use(function (err, req, res, next) {
  if (err.name === "UnauthorizedError") {
    res.send(new ValidationError("token 过期").toResponseJSON());
  } else if (err instanceof ServiceError) {
    res.send(err.toResponseJSON())
  } else if (err instanceof multer.MulterError) {
    let errMessageMap = {
      "LIMIT_FILE_SIZE": "文件大小超过限制,最大为2M",
      "LIMIT_FILE_COUNT": "文件数量超过限制,最多为1个"
    }
    res.send(new UploadError(errMessageMap[err.code]).toResponseJSON())
  } else {
    res.send(new UnknownError().toResponseJSON())
  }
  console.log(err)
});

module.exports = app;
